﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.IO;
using Aspose.Excel;

namespace LenderClearingHouse
{
  public partial class LvreoMasterListEx : InvestorAdminPage
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      listFilter.SearchButton.Click += new ImageClickEventHandler(SearchButton_Click);
      RadAjaxManager.AjaxSettings.AddAjaxSetting(Grid, Grid);

      this.Grid.ItemEvent += new GridItemEventHandler(Grid_ItemEvent);
      this.Grid.ItemCreated += new GridItemEventHandler(Grid_ItemCreated);

      if (!IsPostBack)
      {
        DataAccess da = new DataAccess();
        DataTable tbl = da.ExecuteSQL("select * from Config");

        foreach (DataRow dr in tbl.Rows)
        {
          if (dr["Key"].ToString() == "PercentT1")
          {
            tbT1.Text = dr["Value"].ToString().Replace(",", ".");
          }
          else if (dr["Key"].ToString() == "PercentAA1")
          {
            tbAA1.Text = dr["Value"].ToString().Replace(",", ".");
          }
        }
      }
    }

    protected override void Grid_ItemDataBound(object sender, GridItemEventArgs e)
    {
        base.Grid_ItemDataBound(sender, e);

        if (!(e.Item is GridDataItem)) return;

        GridDataItem itm = e.Item as GridDataItem;
        DataRowView drw = itm.DataItem as DataRowView;

        if (drw["recorded_b"] != DBNull.Value && drw["recorded_b"].ToString() != "")
        {
            itm.BackColor = System.Drawing.Color.FromArgb(204, 153, 255);
        }
        else
        {
            if (drw["InvestorName"] != DBNull.Value && drw["InvestorName"].ToString() != "")
            {
                itm.BackColor = System.Drawing.Color.Yellow;
            }
        }
    }

    void Grid_ItemEvent(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditFormItem)
        {
            if (!((e.Item as GridEditFormItem).DataItem is DataRowView)) return;

            DataRowView drw = (DataRowView)(e.Item as GridEditFormItem).DataItem;
            if (drw == null) return;

            if (drw["NetProfit2"] != DBNull.Value)
            {
                Session["NetProfit"] = Convert.ToInt32(drw["NetProfit2"]);
            }
            else Session["NetProfit"] = 0;

            Session["PropertyLocation"] = Convert.ToString(drw["PropertyLocation"]);
            Session["InvestorName"] = Convert.ToString(drw["InvestorName"]);
            Session["Bedrooms"] = Convert.ToString(drw["Bedrooms"]);
            Session["Bathrooms"] = Convert.ToString(drw["Bathrooms"]);
            Session["ConstructYear"] = Convert.ToString(drw["ConstructYear"]);
            Session["GarageSqft"] = Convert.ToString(drw["GarageSqft"]);
            Session["Pool"] = Convert.ToString(drw["Pool"]);
            Session["TotalSqft"] = Convert.ToString(drw["TotalSqft"]);
        }
    }

    private void Grid_ItemCreated(object sender, GridItemEventArgs e)
    {
      /*if (e.Item is GridEditableItem && e.Item.IsInEditMode)
      {
        //edit will be the first control in the Controls collection of the corresponding cell  
        TextBox edt = (e.Item as GridEditableItem)["RehabCosts"].Controls[0] as TextBox;
        edt.ReadOnly = true;
      }*/
    }

    protected override void grid_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridPagerItem)
        {
            GridPagerItem item = e.Item as GridPagerItem;
            RadComboBox combo = (RadComboBox)item.FindControl("PageSizeComboBox");

            RadComboBoxItem newItem = combo.Items.FindItemByValue("100");
            if (newItem == null)
            {
                RadComboBoxItem citem = new RadComboBoxItem("100", "100");
                citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                combo.Items.Add(citem);
            }
            else
            {
                newItem.Text = "100";
            }

            newItem = combo.Items.FindItemByValue("1000000");
            if (newItem == null)
            {
                RadComboBoxItem citem = new RadComboBoxItem("ALL", "1000000");
                citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                combo.Items.Add(citem);
            }
            else
            {
                newItem.Text = "ALL";
            }
        }
        else if (e.Item is GridDataItem)
        {
            GridDataItem itm = e.Item as GridDataItem;
            DataRowView drw = itm.DataItem as DataRowView;
            if (drw["Recorded_B"] != DBNull.Value)
            {
                itm.BackColor = System.Drawing.Color.FromArgb(204, 153, 255);
            }
        }
    }

    protected override bool AllowDelete
    {
      get
      {
        return false;
      }
    }

    protected override bool AllowInsert
    {
      get
      {
        return false;
      }
    }

    void SearchButton_Click(object sender, ImageClickEventArgs e)
    {
      Grid.Rebind();
      listFilter.ClearFilter();
    }

    protected override string GetPropertyDetailsColumnEditorID()
    {
      return edTextBox.ID;
    }

    protected override Control GetGridContainer()
    {
      return phGrid;
    }

    protected override string GetDataSourceID()
    {
      return sqlDataSource.ID;
    }

    protected void lnkExportToExcel_Click(object sender, EventArgs e)
    {
      Excel ex = Utilities.GetExcel();
      ex.Open(Server.MapPath("~/ExcelTemplate/FinancialAnalysis.xls"));
      Worksheet ws = ex.Worksheets[0];

      DataAccess da = new DataAccess();
      DataTable dt = da.ExecuteSQL(string.Format("getLvreo_MasterListEx '{0}', '{1}', '{2}'",
        GetListFilterControl().Apn,
        GetListFilterControl().Address,
        GetListFilterControl().Zip));
      
      int startRow = 2;
      Utilities.GridToExcel(dt, Grid, ws, false, ref startRow);
      ex.Save("FinancialAnalysisDownload.xls", FileFormatType.Excel2003, SaveType.OpenInExcel, HttpContext.Current.Response);
      //wb.Save(HttpContext.Current.Response, "FinancialAnalysis.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
      HttpContext.Current.Response.End(); 
    }

    protected void lnkRefreshGrid_Click(object sender, EventArgs e)
    {
      Grid.Rebind();
    }

    protected void lnkClearList_Click(object sender, EventArgs e)
    {
      //DataAccess da = new DataAccess();
      //if (da.ExecuteSQLRowCount("clearLvreo_MasterList") > 0)
      //{
      //  CountsControl.SetMessage("LVREO List deleted.");
      //  Grid.Rebind();
      //}
      //else { CountsControl.SetMessage("No properties to delete."); }
    }

    protected void lnkClearImages_Click(object sender, EventArgs e)
    {
      DataAccess da = new DataAccess();

      //Delete Images
      string[] fileImagePaths = Directory.GetFiles(Server.MapPath("~/DocSecure/LVREO/PropertyImages/"));
      foreach (string filePath in fileImagePaths)
        File.Delete(filePath);

      //Delete documents
      string[] fileDocPaths = Directory.GetFiles(Server.MapPath("~/DocSecure/LVREO/PropertyDocuments/"));
      foreach (string filePath in fileDocPaths)
        File.Delete(filePath);

      da.ExecuteSQLNonQuery("clearLvreo_PropertyDocsAndImages");

      //CountsControl.SetMessage("All Docs and Images have been deleted.");
    }

    protected void sqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
      //DataAccess da = new DataAccess();
      //CountsControl.SetCounts(
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Postponed'"),
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Cancelled'"),
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Sold To Bank'"),
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Sold To 3rd Party'"));
    }

    protected override SqlDataSource GetSqlDataSource()
    {
      return sqlDataSource;
    }

    protected override ListFilterControl GetListFilterControl()
    {
      return listFilter;
    }

    protected override bool IsEditable()
    {
      return CurrentUser.UserRole == UserRole.SuperAdmin;
    }

    protected override SourcePage GetSourcePage()
    {
      return SourcePage.LvreoList;
    }

    protected override void SetupSqlDataSource(SqlDataSource dataSource)
    {
      base.SetupSqlDataSource(dataSource);

      dataSource.Selecting += new SqlDataSourceSelectingEventHandler(dataSource_Selecting);
    }

    void dataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
      e.Command.Parameters["@showAllUnassigned"].Value = showAllUnassigned;
    }

    bool showAllUnassigned = false;

    protected void lnkShowUnassigned_Click(object sender, EventArgs e)
    {
      showAllUnassigned = true;
      Grid.Rebind();
    }

    protected override void SetupParameters(ParameterCollection coll)
    {
      coll.Add(new Parameter("Apn"));
      coll.Add(new Parameter("PropertyLocation"));
      coll.Add(new Parameter("ZipCode"));
      coll.Add(new Parameter("Stories"));
      coll.Add(new Parameter("ConstructYear"));
      coll.Add(new Parameter("TotalSQft"));
      coll.Add(new Parameter("Bedrooms"));
      coll.Add(new Parameter("Bathrooms"));
      coll.Add(new Parameter("GarageSqft"));
      coll.Add(new Parameter("Pool"));
      coll.Add(new Parameter("Spa"));
      coll.Add(new Parameter("Recorded_B"));
	    coll.Add(new Parameter("PurchasePrice"));
	    coll.Add(new Parameter("RehabCosts"));
	    coll.Add(new Parameter("EMD"));
	    coll.Add(new Parameter("Reimb"));
	    coll.Add(new Parameter("Insur"));
	    coll.Add(new Parameter("DateAccept"));
	    coll.Add(new Parameter("StartDate"));
	    coll.Add(new Parameter("EstimatedSale"));
      coll.Add(new Parameter("Assmts"));
      coll.Add(new Parameter("FeePercent"));
      coll.Add(new Parameter("NetProfit2"));
    }

    GridTemplateColumn AddDollarColumn(GridColumnCollection columns, string fieldName, string headerText, bool readOnly, int editFormColumnIndex, string format = "")
    {
        GridTemplateColumn gtc = new GridTemplateColumn()
        {
            UniqueName = fieldName,
            HeaderText = headerText,
            ItemTemplate = new DollarColumn(fieldName, format),
            EditItemTemplate = new CurrencyColumnEdit(fieldName),
            ConvertEmptyStringToNull = false,
            EditFormColumnIndex = editFormColumnIndex,
            DataField = fieldName,
            SortExpression = fieldName,
            ReadOnly = readOnly
        };
        gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
        gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);

        return gtc;
    }

    protected override void CreateColumns(GridColumnCollection columns)
    {
      base.CreateColumns(columns);

      Utilities.HideColumn(columns, "ListingStatus");
      Utilities.HideColumn(columns, "Source");
      Utilities.HideColumn(columns, "DateRecorded");
      Utilities.HideColumn(columns, "EscrowCompany");
      Utilities.HideColumn(columns, "AssessorDesc");
      Utilities.HideColumn(columns, "HOA");
      Utilities.HideColumn(columns, "LotSize");
      Utilities.HideColumn(columns, "PrelistStatus");
      Utilities.HideColumn(columns, "MiscNotes");
      Utilities.HideColumn(columns, "LandUse");
      Utilities.HideColumn(columns, "Phase");

      int index = 1;
      Utilities.MoveColumn(columns, "InvestorName", ref index);

      columns.Add(Utilities.CreateTemlateDateColumn("StartDate", "Start Date", 3));
      ((GridTemplateColumn)columns.FindByDataField("StartDate")).ConvertEmptyStringToNull = false;
      Utilities.MoveColumn(columns, "StartDate", ref index);

      columns.Add(Utilities.CreateBoundColumn("DeedRestrictions", "Deed Restrictions", false, 3));
      Utilities.MoveColumn(columns, "DeedRestrictions", ref index);

      Utilities.MoveColumn(columns, "Apn", ref index);
      Utilities.MoveColumn(columns, "PropertyLocation", ref index);
      ++index;
      Utilities.MoveColumn(columns, "ZipCode", ref index);
              
      GridTemplateColumn gtc = new GridTemplateColumn()
      {
          UniqueName = "Assmts",
          HeaderText = "Assmts",
          ItemTemplate = new SpanColumn("Assmts"),
          EditItemTemplate = new YesNoColumnEdit("Assmts"),
          EditFormColumnIndex = 1,
          DataField = "Assmts",
          SortExpression = "Assmts"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Insert(index, gtc);
      ++index;

      /*columns.Add(Utilities.CreateBoundColumn("Insur", "Insur", false, 3));
      Utilities.MoveColumn(columns, "Insur", ref index);

      columns.Add(Utilities.CreateTemlateDateColumn("DateAccept", "Date Accept", 3));
      ((GridTemplateColumn)columns.FindByDataField("DateAccept")).ConvertEmptyStringToNull = false;
      Utilities.MoveColumn(columns, "DateAccept", ref index);*/

      index = GetColumnIndex(columns, "PurchasePrice") + 1;
      
      gtc = new GridTemplateColumn()
      {
          UniqueName = "RehabCosts",
          HeaderText = "Rehab Estimate",
          ItemTemplate = new DollarColumn("RehabCosts"),
          EditItemTemplate = new RehabCostsColumn("RehabCosts"),
          EditFormColumnIndex = 0,
          DataField = "RehabCosts",
          SortExpression = "RehabCosts"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.RemoveAt(GetColumnIndex(columns, "RehabCosts"));
      columns.Insert(index, gtc);

      ++index;

      gtc = AddDollarColumn(columns, "CurrentRehabCosts", "Rehab Actual", true, 3, "#0.00");
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "CurrentRehabCosts", ref index);

      gtc = AddDollarColumn(columns, "PurchaseNoteTotal", "Purchase/Note Total", true, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "PurchaseNoteTotal", ref index);

      gtc = AddDollarColumn(columns, "PurchaseCostSqft", "Purchase Cost/Sqft", true, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "PurchaseCostSqft", ref index);

      gtc = AddDollarColumn(columns, "EstimatedSale", "Estimated Sale", false, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "EstimatedSale", ref index);

      gtc = AddDollarColumn(columns, "ActualSale", "Actual Sale", true, 3, "#0.00");
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "ActualSale", ref index);

      gtc = AddDollarColumn(columns, "ActualvsEstimate", "Actual vs Estimate", true, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "ActualvsEstimate", ref index);

      GridBoundColumn col = Utilities.CreateBoundColumn("ActualvsEstimatePercent", "% Act vs Est", true, 3);
      col.ReadOnly = true;
      columns.Add(col);
      Utilities.MoveColumn(columns, "ActualvsEstimatePercent", ref index);

      gtc = AddDollarColumn(columns, "CostOfSale", "Cost Of Sale", true, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "CostOfSale", ref index);

      gtc = AddDollarColumn(columns, "SaleCostSqft", "Sale Cost/Sqft", true, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "SaleCostSqft", ref index);

      gtc = AddDollarColumn(columns, "ClosingCost", "Closing Cost", true, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "ClosingCost", ref index);

      gtc = AddDollarColumn(columns, "NetDemandToEscrow", "Net Demand To Escrow", true, 3);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "NetDemandToEscrow", ref index);
        
      gtc = new GridTemplateColumn()
      {
          UniqueName = "NetProfit2",
          HeaderText = "NetProfit",
          ItemTemplate = new DollarColumn("NetProfit2"),
          EditItemTemplate = new NetProfitColumn("NetProfit2"),
          EditFormColumnIndex = 0,
          DataField = "NetProfit2",
          SortExpression = "NetProfit2"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "NetProfit2", ref index);

      col = Utilities.CreateBoundColumn("PercentOfProfitVsPurchase", "% Of Profit vs Purchase", false, 3);
      col.ReadOnly = true;
      columns.Add(col);
      Utilities.MoveColumn(columns, "PercentOfProfitVsPurchase", ref index);

      col = Utilities.CreateBoundColumn("CostToARV", "Cost To ARV", false, 3);
      col.ReadOnly = true;
      columns.Add(col);
      Utilities.MoveColumn(columns, "CostToARV", ref index);

      gtc = ((GridTemplateColumn)columns.FindByDataField("CloseDate"));
      gtc.DataField = "Recorded_B";
      gtc.EditFormColumnIndex = 3;
      gtc.UniqueName = "Recorded_B";
      gtc.ItemTemplate = new SpanDateColumn("Recorded_B");
      gtc.EditItemTemplate = new DateColumnEdit("Recorded_B");
      gtc.SortExpression = "Recorded_B";
      Utilities.MoveColumn(columns, "Recorded_B", ref index);

      col = Utilities.CreateBoundColumn("TotalDays", "Total Days", false, 3);
      col.ReadOnly = true;
      columns.Add(col);
      Utilities.MoveColumn(columns, "TotalDays", ref index);

      gtc = Utilities.CreateTemlateSpanColumn("Type", "Type", 3);
      gtc.EditItemTemplate = new TypeColumnEdit("Type", GetSourcePage());
      columns.Add(gtc);
      Utilities.MoveColumn(columns, "Type", ref index);
      
      /*col = new GridBoundColumn();
      col.DataField = "EMD";
      col.HeaderText = "EMD";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Insert(3, col);

      col = new GridBoundColumn();
      col.DataField = "Reimb";
      col.HeaderText = "Reimb";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Insert(4, col);
                        
      col = new GridBoundColumn();
      col.DataField = "FeePercent";
      col.HeaderText = "Fee Percent";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Add(col);
        
      gtc = new GridTemplateColumn()
      {
        UniqueName = "PurchasePrice",
        HeaderText = "Purchase Price",
        ItemTemplate = new DollarColumn("PurchasePrice"),
        EditItemTemplate = new BuyerPurchasePriceColumn("PurchasePrice"),
        EditFormColumnIndex = 0,
        DataField = "PurchasePrice",
        SortExpression = "PurchasePrice"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      index = GetColumnIndex(columns, "PurchasePrice");
      columns.RemoveAt(index);
      columns.Insert(index, gtc);*/
     
    }

    class NetProfitColumn : IBindableTemplate
    {
        string columnName;
      
        public NetProfitColumn(string columnName)
        {
            this.columnName = columnName;
        }

        public void InstantiateIn(Control container)
        {
            HtmlGenericControl span = new HtmlGenericControl("div");
            span.Style.Value = "cursor:pointer; background-color:Gray; font-weight: bold; color: White";
            span.ClientIDMode = ClientIDMode.Static;
            span.ID = "div-net-profit";
            span.DataBinding += new EventHandler(span_DataBinding);
            span.Attributes.Add("onclick", "OpenNetSheetDialog();");
            container.Controls.Add(span);
        }

        void span_DataBinding(object sender, EventArgs e)
        {
            HtmlGenericControl span = (HtmlGenericControl)sender;
            GridItem container = (GridItem)span.NamingContainer;
            span.InnerText = ((int)(container.DataItem as DataRowView)[columnName]).ToString("c");
        }

        public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
        {
            var result = new System.Collections.Specialized.OrderedDictionary();
            result.Add(columnName, HttpContext.Current.Session["NetProfit"]);
            return result;
        }
    }

    class BuyerPurchasePriceColumn : IBindableTemplate
    {
      string columnName;

      public BuyerPurchasePriceColumn(string columnName)
      {
        this.columnName = columnName;
      }

      public void InstantiateIn(Control container)
      {
        HtmlGenericControl span = new HtmlGenericControl("div");
        span.ClientIDMode = ClientIDMode.Static;
        span.ID = "div-buyer-purchase-price";
        span.DataBinding += new EventHandler(span_DataBinding);
        container.Controls.Add(span);

        span = new HtmlGenericControl("div");
        span.Style.Value = "display:none;";
        span.ClientIDMode = ClientIDMode.Static;
        span.ID = "div-buyer-purchase-price-value";
        span.DataBinding += new EventHandler(spanValue_DataBinding);
        container.Controls.Add(span);

        span = new HtmlGenericControl("div");
        span.Style.Value = "display:none;";
        span.ClientIDMode = ClientIDMode.Static;
        span.ID = "div-propertyid";
        span.DataBinding += new EventHandler(spanProperty_DataBinding);
        container.Controls.Add(span);

      }

      void span_DataBinding(object sender, EventArgs e)
      {
        HtmlGenericControl span = (HtmlGenericControl)sender;
        GridItem container = (GridItem)span.NamingContainer;
        try
        {
            span.InnerText = ((decimal)(container.DataItem as DataRowView)[columnName]).ToString("c");
        }
        catch { span.InnerText = "0"; }
      }

      void spanValue_DataBinding(object sender, EventArgs e)
      {
        HtmlGenericControl span = (HtmlGenericControl)sender;
        GridItem container = (GridItem)span.NamingContainer;
          try
          {
            span.InnerText = ((decimal)(container.DataItem as DataRowView)[columnName]).ToString();
          }
        catch { span.InnerText = "0"; }
      }

      void spanProperty_DataBinding(object sender, EventArgs e)
      {
        HtmlGenericControl span = (HtmlGenericControl)sender;
        GridItem container = (GridItem)span.NamingContainer;
        span.InnerText = ((long)(container.DataItem as DataRowView)["PropertyId"]).ToString();
      }

      public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
      {
        var result = new System.Collections.Specialized.OrderedDictionary();
        result.Add(columnName, HttpContext.Current.Session["BuyerPurchasePrice"]);
        return result;
      }
    }

    class RehabCostsColumn : IBindableTemplate
    {
      string columnName;

      public RehabCostsColumn(string columnName)
      {
        this.columnName = columnName;
      }

      public void InstantiateIn(Control container)
      {
        HtmlGenericControl span = new HtmlGenericControl("div");
        span.ClientIDMode = ClientIDMode.Static;
        span.ID = "div-rehab-costs";
        span.DataBinding += new EventHandler(span_DataBinding);
        container.Controls.Add(span);

        span = new HtmlGenericControl("div");
        span.Style.Value = "display:none;";
        span.ClientIDMode = ClientIDMode.Static;
        span.ID = "div-rehab-costs-value";
        span.DataBinding += new EventHandler(spanValue_DataBinding);
        container.Controls.Add(span);
      }

      void span_DataBinding(object sender, EventArgs e)
      {
        HtmlGenericControl span = (HtmlGenericControl)sender;
        GridItem container = (GridItem)span.NamingContainer;
        DataRowView drv = container.DataItem as DataRowView;
        if (drv[columnName] != DBNull.Value)
            span.InnerText = ((decimal)(drv)[columnName]).ToString("c");
        else
            span.InnerText = ((decimal)0).ToString("c");
      }

      void spanValue_DataBinding(object sender, EventArgs e)
      {
        HtmlGenericControl span = (HtmlGenericControl)sender;
        GridItem container = (GridItem)span.NamingContainer;
        DataRowView drv = container.DataItem as DataRowView;
        if (drv[columnName] != DBNull.Value)
            span.InnerText = ((decimal)(drv)[columnName]).ToString();
        else
            span.InnerText = ((decimal)0).ToString();
      }

      void spanProperty_DataBinding(object sender, EventArgs e)
      {
        HtmlGenericControl span = (HtmlGenericControl)sender;
        GridItem container = (GridItem)span.NamingContainer;
        span.InnerText = ((long)(container.DataItem as DataRowView)["PropertyId"]).ToString();
      }

      public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
      {
        var result = new System.Collections.Specialized.OrderedDictionary();
        result.Add(columnName, HttpContext.Current.Session["RehabCosts"]);
        return result;
      }
    }

    int GetColumnIndex(GridColumnCollection columns, string dataField)
    {
      for (int i = 0; i < columns.Count; i++)
      {
        if (columns[i].IsBoundToFieldName(dataField)) return i;
      }
      return 0;
    }

    /*void HideColumn(GridColumnCollection columns, string dataField)
    {
      GridEditableColumn gc = (GridEditableColumn)columns.FindByUniqueName(dataField);
      gc.ReadOnly = true;
      gc.Visible = false;
    }*/

    protected void btnSave_Click(object sender, EventArgs e)
    {
      DataAccess da = new DataAccess();

      da.ExecuteSQLNonQuery(
        string.Format("update Config set [Value] = '{0}' where [Key] = 'PercentT1'",
        tbT1.Text));

      da.ExecuteSQLNonQuery(
        string.Format("update Config set [Value] = '{0}' where [Key] = 'PercentAA1'",
        tbAA1.Text));
    }
  }

  class TypeColumnEdit : IBindableTemplate
  {
      string columnName;
      SourcePage sourcePage;

      public TypeColumnEdit(string columnName, SourcePage sourcePage)
      {
          this.columnName = columnName;
          this.sourcePage = sourcePage;
      }

      public void InstantiateIn(Control container)
      {
          DropDownList ddl = new DropDownList();
          ddl.ID = "ddlType" + columnName;
          ddl.Width = Unit.Pixel(100);

          ddl.Items.Add(new ListItem("SFR", "SFR"));
          ddl.Items.Add(new ListItem("4Px", "4Px"));
          ddl.Items.Add(new ListItem("APT", "APT"));
          ddl.Items.Add(new ListItem("TWN", "TWN"));
          ddl.Items.Add(new ListItem("CON", "CON"));
          ddl.Items.Add(new ListItem("CMM", "CMM"));
          ddl.Items.Add(new ListItem("DUP", "DUP"));
          ddl.Items.Add(new ListItem("HIR", "HIR"));
          ddl.Items.Add(new ListItem("OTH", "OTH"));
          ddl.DataBinding += new EventHandler(ddl_DataBinding);

          container.Controls.Add(ddl);
      }

      void ddl_DataBinding(object sender, EventArgs e)
      {
          DropDownList ddl = (DropDownList)sender;
          GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
          DataRowView drw = container.DataItem as DataRowView;
          if (drw == null) return;

          string val = drw["Type"].ToString();
          if (ddl.Items.FindByValue(val) != null)
              ddl.SelectedValue = val;
          else
              ddl.SelectedValue = "OTH";

      }

      public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
      {
          OrderedDictionary od = new OrderedDictionary();
          od.Add(columnName, ((DropDownList)(((GridEditFormItem)(container)).FindControl("ddlType" + columnName))).SelectedValue);
          return od;
      }
  }
}